# -*- coding: utf-8 -*-
import os
import re
import time
import MySQLdb
import datx
import ipdb
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse
from comment.models import Comment
from zhp_blog.models import Article, Category, ArticleUpDown
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import json
from django.shortcuts import render
from django.db.models import Q
from django.db import connection
config = {"host": "94.191.114.51",
              "port": 3506,
              'user': 'root',
              "passwd": 'zhp123456',
              "db": 'zhp_blog',
              "charset": "utf8mb4"}
db = MySQLdb.connect(**config)
cur = db.cursor()


def index(request):
    try:
        life_info = Article.objects.all().order_by('-edit_time')

        page = request.GET.get('page')
        paginator = Paginator(life_info,5)  #条数
        try:
            contacts = paginator.page(page)  # contacts为Page对象！
        except PageNotAnInteger:
            contacts = paginator.page(1)
        except EmptyPage:
            contacts = paginator.page(paginator.num_pages)
        data = []
        for m in contacts:
            edit = m.edit_time
            edit = time.localtime(edit)

            edit_time = time.strftime("%Y-%m-%d %H:%M:%S", edit)
            cate_name = Category.objects.filter(category_id=m.category_id)
            re_detail = re.compile('<!--[^>]*-->')
            detail = re_detail.sub('', m.detail).replace('&nbsp;', '').replace('&lt;', '')
            # print detail
            # info = BeautifulSoup(str(detail),'html.parser')
            # print info.textarea.get_text()
            # print '=========='
            # print m.title

            for k in cate_name:
                data.append({
                    'category_names': k.category_name,
                    'title': m.title,
                    'detail': detail,
                    'edit_time': edit_time,
                    'edit_user_name': m.edit_user_name,
                    'hid': m.hid,
                    'count': m.count,
                    'like_count': m.like_count
                })

        cate_name = Category.objects.all()
        info_count = Article.objects.count()
        hot_info = Article.objects.filter(~Q(count=0)).count()

        # # 时间归档

        cur.execute('select date_format(create_time, "%Y年%m月") months from zhp_blog.article group by months;')
        time_list = cur.fetchall()
        print time_list

        count_title = Article.objects.all().order_by('-count')[0:5]
        # 最新文章
        new_title = Article.objects.all().order_by('-edit_time')[0:5]
    except Article.DoesNotExist:
        return render(request, '404.html')

    return render(request, 'blog/index.html',
                  {'new_title': new_title, 'time_list': time_list, 'count_title': count_title, 'cate_name': cate_name,
                   'data': data, 'hot_info': hot_info,
                   'contacts': contacts, 'info_count': info_count})


def cate_list(request, category_id):
    '''
    分类列表
    :param request:
    :param category_id:
    :return:
    '''
    try:
        life_info = Article.objects.filter(category_id=(category_id)).order_by('-count')

        page = request.GET.get('page')
        paginator = Paginator(life_info, 5)  # 条数
        try:
            contacts = paginator.page(page)  # contacts为Page对象！
        except PageNotAnInteger:
            contacts = paginator.page(1)
        except EmptyPage:
            contacts = paginator.page(paginator.num_pages)
        if life_info:
            data = []
            for i in contacts:
                edit = i.edit_time
                edit = time.localtime(edit)
                edit_time = time.strftime("%Y-%m-%d %H:%M:%S", edit)
                data.append({
                    'edit_time': edit_time,
                    'hid': i.hid,
                    'title': i.title,
                    'edit_user_name': i.edit_user_name,
                    'count': i.count,
                    'like_count': i.like_count
                })

        cate_name = Category.objects.all()
        count_title = Article.objects.all().order_by('-count')[0:5]
        info_count = Article.objects.count()
        hot_info = Article.objects.filter(~Q(count=0)).count()
        # # 时间归档

        cur.execute('select date_format(create_time, "%Y年%m月") months from zhp_blog.article group by months;')
        time_list = cur.fetchall()
        # 最新文章
        new_title = Article.objects.all().order_by('-edit_time')[0:5]

        return render(request, 'blog/cate_index.html',
                      {'new_title': new_title, 'time_list': time_list, 'life_info': life_info, 'data': data,
                       'contacts': contacts, 'info_count': info_count, 'hot_info': hot_info,
                       'edit_time': edit_time, 'cate_name': cate_name, 'count_title': count_title})
    except:
        return render(request, '404.html')


def detail(request, hid):
    '''文章详情页,评论 '''
    nums = 1
    try:
        text = Article.objects.get(hid=hid)
        cate_name = Category.objects.get(category_id=text.category_id)
        edit = time.localtime(text.edit_time)
        edit_time = time.strftime("%Y-%m-%d %H:%M:%S", edit)

    except Exception as e:

        return render(request, '404.html')
    else:
        count = text.count
        text.count = count + nums
        text.save()
    comments = Comment.objects.filter(hid=hid)  # 所有的评论
    info_count = Article.objects.get(hid=hid)

    hot_info = Article.objects.filter(~Q(count=0)).count()

    return render(request, 'blog/single.html', {'text': text,'info_count': info_count.count, 'hot_info': hot_info,'cate_name':cate_name,
                                                'comments': comments, 'hid': hid, 'edit_time': edit_time})


def post(request):
    ''' ip 查询'''
    post_info = request.POST
    ip = post_info.get('ip', '')
    if not ip:
        return HttpResponse('ip 不能为空')
    try:
        db = ipdb.City("../zhp_blog/zhp_blog/ipipfree.ipdb")
        info = db.find(ip, 'CN')
        # c = datx.City('../zhp_blog/zhp_blog/17monipdb.datx')
        # info = c.find(ip)

        return HttpResponse(info)
    except Exception as e:
        print e
        return render(request, '404.html')


def cat_title(request):
    '''标题查询'''
    # 'title'
    # 根据title 进行模糊查询
    post_info = request.POST
    title = post_info.get('title', '')

    if not title:
        return HttpResponse('请输入标题')
    info = Article.objects.filter(Q(title__contains=title))
    data = []
    info_count = Article.objects.count()
    hot_info = Article.objects.filter(~Q(count=0)).count()
    for i in info:
        edit = i.edit_time
        edit = time.localtime(edit)
        edit_time = time.strftime("%Y-%m-%d %H:%M:%S", edit)

        data.append({
            'title': i.title,
            'detail': i.detail,
            'hid': i.hid,
            'add_time': edit_time,
            'edit_username': i.edit_user_name,
            'count': i.count,
            'like_count': i.like_count,

        })
    count_title = Article.objects.all().order_by('-count')[0:5]
    cate_name = Category.objects.all()
    # # 时间归档

    cur.execute('select date_format(create_time, "%Y年%m月") months from zhp_blog.article group by months;')
    time_list = cur.fetchall()
    # 最新文章
    new_title = Article.objects.all().order_by('-edit_time')[0:5]

    return render(request, 'blog/cat_title.html',
                  {'new_title': new_title, 'time_list': time_list, 'cate_name': cate_name, 'count_title': count_title,
                   'data': data, 'info_count': info_count, 'hot_info': hot_info})


def article_like(request):
    post_info = request.POST
    hid = post_info.get('hid')
    action = post_info.get('action')
    action = json.loads(action)
    if hid and action:
        try:
            article = Article.objects.get(hid=hid)
            if action == 'like':
                article.is_like = 1
            else:
                article.is_like = 0
            ard = Article.objects.create(hid=hid, is_like=action)
            return HttpResponse({'status': 'ok'})
        except:
            pass
    return HttpResponse({'status': 'no'})


def digg(request):
    num = 1
    post_info = request.POST
    if post_info:
        is_up = post_info.get('is_up', '')
        hid = post_info.get('hid', '')
        is_up = json.loads(is_up)
        if request.META.has_key('HTTP_X_FORWARD_FOR'):
            user_ip = request.META['HTTP_X_FORWARD_FOR']
        else:
            user_ip = request.META['REMOTE_ADDR']

        obj = ArticleUpDown.objects.filter(user_ip=user_ip, article_id=hid, is_up=is_up)  # 没有记录就保存点赞
        response = {"state": True}
        if not obj:

            if 'True' in str(is_up):
                try:
                    text = Article.objects.get(hid=hid)
                except Exception as e:
                    print e
                    return render(request, '404.html')
                else:
                    count = text.like_count
                    text.like_count = count + num
                    text.save()
            else:
                try:
                    text = Article.objects.get(hid=hid)
                except Exception as e:
                    print e
                    return render(request, '404.html')
                else:
                    count = text.unlike_count
                    text.unlike_count = count + num
                    text.save()
            ard = ArticleUpDown(is_up=is_up, article_id=hid, user_ip=user_ip)
            ard.save()
            response['state'] = True
            response['handled'] = is_up
            response = json.dumps(response)
            return HttpResponse(response, mimetype='application/javascript')
        else:
            response['state'] = False
            response['handled'] = is_up
            response = json.dumps(response)
            return HttpResponse(response, mimetype='application/javascript')
    else:
        return HttpResponse('ok')


def time_handle(request, times):
    year = re.match(r"(\d+)年", str(times)).group(1)
    month = re.search(r"年(\d+)月", str(times)).group(1)
    life_info = Article.objects.filter(create_time__year=year, create_time__month=month).all().order_by("-create_time")
    page = request.GET.get('page')
    paginator = Paginator(life_info, 5)  # 条数
    try:
        contacts = paginator.page(page)  # contacts为Page对象！
    except PageNotAnInteger:
        contacts = paginator.page(1)
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages)
    data = []
    cate_name = Category.objects.all()  # 分类
    for m in contacts:
        edit = m.edit_time
        edit = time.localtime(edit)
        edit_time = time.strftime("%Y-%m-%d %H:%M:%S", edit)
        cate_name = Category.objects.filter(category_id=m.category_id)
        re_detail = re.compile('<!--[^>]*-->')
        detail = re_detail.sub('', m.detail)
        for k in cate_name:
            data.append({
                'category_names': k.category_name,
                'title': m.title,
                'detail': detail,
                'edit_time': edit_time,
                'edit_user_name': m.edit_user_name,
                'hid': m.hid,
                'count': m.count,
                'like_count': m.like_count
            })
    count_title = Article.objects.all().order_by('-count')[0:5]  # 排行
    # 时间归档
    cur.execute('select date_format(create_time, "%Y年%m月") months from zhp_blog.article group by months;')
    time_list = cur.fetchall()
    # 最新文章
    new_title = Article.objects.all().order_by('-edit_time')[0:5]
    # 热门
    info_count = Article.objects.count()
    hot_info = Article.objects.filter(~Q(count=0)).count()

    return render(request, "blog/time_index.html", {'info_count':info_count,'hot_info':hot_info,
                                                    'new_title':new_title,'data': data,'cate_name': cate_name,'time_list': time_list,
                                                    'count_title': count_title,'contacts': contacts})


def about_me(request):
    info_count = Article.objects.count()
    hot_info = Article.objects.filter(~Q(count=0)).count()
    return render(request, "blog/about.html",{'info_count':info_count,'hot_info':hot_info})


def txt(request):

    return HttpResponse('30785de5a118f6203da5f321db790ce1')